<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import Map from '@/components/Map.vue'
import EchartsMap from '@/components/EchartsMap.vue'
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import VideoPlayer from '@/components/VideoPlayer.vue'
import VideoManageDialog from '@/components/VideoManageDialog.vue'
import ReportDialog from '@/views/screen/report/ReportDialog.vue'
import TitleBlock from './components/TitleBlock.vue'
import OrgCount from './components/OrgCount.vue'
import RunDataCount from './components/RunDataCount.vue'
import OrgCityRateBar from './components/OrgCityRateBar.vue'
import EventList from './components/EventList.vue'
import AlarmCount from './components/AlarmCount.vue'
import LineToday from './components/LineToday.vue'
import TrendBox from './components/TrendBox.vue'
import DeviceOnline from './components/DeviceOnline.vue'
import { useUserStore } from '@/store/userStore'
import WebSocketService from '@/utils/websocket'
// 导入音频文件
import alarmSoundWarn from '@/assets/sounds/warn-audio.mp3'
import alarmSoundAlarm from '@/assets/sounds/alarm-audio.mp3'
import WorkOrderList from '@/components/WorkOrderList.vue'

const layerType = ref<'yx'>('yx')
const scale = ref(1)

// 地图相关状态
const mapLevel = ref('country')
const areaCode = ref('100000')
const echartsMapRef = ref(null)
const tdMapRef = ref(null)
const currentAreaName = ref('中国')
const districtCenter = ref<[number, number]>([116.397428, 39.90923])
const districtBoundary = ref<any>(null)

const isShowEventList = ref(false)

const userStore = useUserStore()
const powerCode = computed(() => userStore.userInfo?.powerCode)
const unitId = computed(() => userStore.userInfo?.unitId)
console.log(powerCode.value, '==powerCode==')
console.log(unitId.value, '==unitId==')

if (powerCode.value !== 'admin') {
  areaCode.value = unitId.value
}

const isAdmin = computed(() => powerCode.value === 'admin') // 默认设置为false以显示单站模式
watch(isAdmin, (newVal) => {
  console.log(newVal, '==isAdmin==')
}, {
  immediate: true
})
const stationConfig = computed(() => userStore.stationConfig)
const ScreenTitle = computed(() => {
  let title = stationConfig.value?.Text || stationConfig.value?.Title
  if (powerCode.value !== 'admin') {
    return title
  }
  //TitleType: "区域+固定文字"
  if (stationConfig.value?.TitleType === '区域+固定文字') {
    title = `${currentAreaName.value}${title}`
    //将中国替换为全国
    title = title.replace('中国', '全国')
  } else {
    title = stationConfig.value.Title
  }
  return title
})

const isDistrictLevel = computed(() => mapLevel.value === 'district')

const handleAreaClick = (areaInfo: { name: string, code: string, level: string, properties: any }) => {
  console.log('区域点击111:', areaInfo)
  console.log('区域点击222:', areaInfo.properties.center)
  currentAreaName.value = areaInfo.name
  if (areaInfo.level === 'district') {
    setTimeout(() => {
      tdMapRef.value.locateToCoordinates(areaInfo.properties.center)
    }, 300)
  }
}

const backToParentMap = () => {
  mapLevel.value = 'country'
  areaCode.value = ''
}

const backToCenterMap = () => {
  mapLevel.value = 'country'
  areaCode.value = ''
  currentAreaName.value = '全国'
}

const calculateScale = () => {
  const designWidth = 1920
  const designHeight = 1080

  const width = window.innerWidth
  const height = window.innerHeight

  const widthScale = width / designWidth
  const heightScale = height / designHeight

  scale.value = Math.min(widthScale, heightScale)
}

const handleResize = () => {
  // calculateScale()
}

const handleTreeChange = (params: any) => {
  console.log(params, 789)
  if (!params || params.level === 1) {
    areaCode.value = ''
    userStore.userInfo.powerCode = 'admin'
    userStore.setSelectedAreaCode('')
    userStore.fetchStationConfig()
    return
  }
  if ([2, 3].includes(params.level)) {
    areaCode.value = params.value
    userStore.userInfo.powerCode = 'childrenOrg'
    userStore.setSelectedAreaCode(params.value)
    userStore.fetchStationConfig()
    return
  }
}

// 处理刷新事件
const handleRefresh = () => {
  // 调用VideoPlayer组件的刷新方法
  videoPlayerRef.value?.refreshCameras()
}

// 处理视频管理对话框打开
const handleOpenVideoManage = () => {
  showVideoManageDialog.value = true
}

// 处理报表对话框打开
const handleOpenReport = () => {
  showReportDialogVisible.value = true
}

// 处理视频管理刷新
const handleVideoManageRefresh = () => {
  // 调用VideoPlayer组件的刷新方法
  videoPlayerRef.value?.refreshCameras()
}

const getMapLevelName = (level: string): string => {
  const levelMap: Record<string, string> = {
    'country': '中国',
    'province': '省级',
    'city': '市级',
    'district': '区/县级'
  }
  return levelMap[level] || level
}

// WebSocket连接实例
const wsService = ref<WebSocketService | null>(null)
// 最新的预警数据
const lastAlarmData = ref<any>(null)
// 音频元素
const alarmAudio = ref<HTMLAudioElement | null>(null)

// 获取视频元素配置列表
const videoEleList = computed(() => {
  return stationConfig.value?.D001729StationConfigVideoEle || []
})

// 处理全屏事件
const isFullScreen = ref(false)
const handleSetFullScreen = (value: boolean) => {
  isFullScreen.value = value
  //如果全屏，则隐藏面板
  let visibility = ''
  if (value) {
    visibility = 'hidden'
  } else {
    visibility = 'visible'
  }
  //@ts-ignore
  document.querySelector('.left-panel')?.style.setProperty('visibility', visibility)
  //@ts-ignore
  document.querySelector('.right-panel')?.style.setProperty('visibility', visibility)
  //@ts-ignore
  document.querySelector('.header-container')?.style.setProperty('visibility', visibility)
}

// VideoPlayer组件引用
const videoPlayerRef = ref()

// 处理WebSocket消息
const handleWsMessage = (event: any) => {
  try {
    if (event.type === 'alarm') {
      // console.log('收到WebSocket alarm消息:', event.data)
      lastAlarmData.value = { ...event.data }
      //根据AlarmLevel判断播放哪个音频
      handlerAlarmAudioPlay(event.data.AlarmLevel)
    } else if (event.type === 'eventData') {
      // console.log('收到WebSocket eventData消息:', event.data, stationConfig.value)
      // 将数据传递给VideoPlayer组件处理
      videoPlayerRef.value?.processSensorData(event.data)
    }
  } catch (error) {
    console.error('处理WebSocket消息错误:', error)
  }
}

const handlerAlarmAudioPlay = (alarmLevel: string) => {
  //根据stationConfig配置中的 SoundPlay AlarmSoundPlay 判断是否播放音频，需要区分异常和超标
  if (alarmLevel === '异常') {
    alarmAudio.value = new Audio(alarmSoundWarn)
    alarmAudio.value.currentTime = 0
    if (stationConfig.value.SoundPlay) {
      console.log('播放异常音频，次数：', stationConfig.value.SoundPlayTimes)
      if (stationConfig.value.SoundPlayTimes > 0) {
        //遍历SoundPlayTimes次
        for (let i = 0; i < stationConfig.value.SoundPlayTimes; i++) {
          alarmAudio.value.play()
        }
      } else {
        //至少播放一次
        alarmAudio.value.play()
      }
    } else {
      console.log('不播放异常音频')
    }
  }
  if (alarmLevel === '超标') {
    alarmAudio.value = new Audio(alarmSoundAlarm)
    alarmAudio.value.currentTime = 0
    if (stationConfig.value.AlarmSoundPlay) {
      console.log('播放超标音频，次数：', stationConfig.value.AlarmSoundPlayTimes)
      if (stationConfig.value.AlarmSoundPlayTimes > 0) {
        //遍历AlarmSoundPlayTimes次
        for (let i = 0; i < stationConfig.value.AlarmSoundPlayTimes; i++) {
          alarmAudio.value.play()
        }
      } else {
        //至少播放一次
        alarmAudio.value.play()
      } 
    } else {
      console.log('不播放超标音频')
    }
  }
}

// 初始化WebSocket连接
const initWebSocket = () => {
  // 如果已存在连接，直接返回
  if (wsService.value) {
    return
  }

  // 创建新连接
  wsService.value = new WebSocketService({
    onMessage: handleWsMessage,
    onOpen: (event) => {
      console.log('DataScreen组件: WebSocket连接已打开', event)
    },
    onError: (event) => {
      console.error('DataScreen组件: WebSocket连接错误', event)
    },
    onClose: (event) => {
      console.log('DataScreen组件: WebSocket连接已关闭', event)
    }
  })

  // 建立连接
  wsService.value.connect()
}

// 对话框状态
const showVideoManageDialog = ref(false)
const showReportDialogVisible = ref(false)

onMounted(() => {
  window.document.title = '可视化大屏'
  // calculateScale()
  window.addEventListener('resize', handleResize)
  // 预加载音频
  alarmAudio.value = null
  setTimeout(() => {
    // 初始化WebSocket连接
    initWebSocket()
  }, 5000)
  //30分钟刷新一次页面
  setInterval(() => {
    window.location.reload()
  }, 30 * 60 * 1000)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)

  // 组件卸载时关闭WebSocket连接
  if (wsService.value) {
    wsService.value.disconnect()
    wsService.value = null
  }

  // 释放音频资源
  if (alarmAudio.value) {
    alarmAudio.value = null
  }
})

</script>

<template>
  <div class="screen-container" :style="{ transform: `scale(${scale})`, transformOrigin: 'center center' }">
    <Header :title="ScreenTitle" :TextFontSize="stationConfig.TextFontSize" :hasVideo="true" :isAdmin="isAdmin" @tree-change="handleTreeChange" @refresh="handleRefresh" @open-video-manage="handleOpenVideoManage" @open-report="handleOpenReport" />
    <div class="map-wrapper">
      <template v-if="!isAdmin">
        <div class="single-station-wrap">
          <!-- 在单站模式下添加VideoPlayer组件 -->
          <VideoPlayer
            ref="videoPlayerRef"
            :videoEleList="videoEleList"
            :handleWsMessage="handleWsMessage"
            :powerCode="powerCode"
            :areaCode="areaCode"
            @setFullScreen="handleSetFullScreen"
          />
        </div>
      </template>
      <template v-else>
        <template v-if="isDistrictLevel">
          <Map ref="tdMapRef" :layer-type="layerType" :district-code="areaCode" :district-name="currentAreaName"
            :center="districtCenter" :district-boundary="districtBoundary" :highlight-district="true"
            @back-to-parent="backToParentMap" />
        </template>
        <template v-else>
          <EchartsMap ref="echartsMapRef" v-model:map-level="mapLevel" v-model:area-code="areaCode"
            @area-click="handleAreaClick" />
        </template>
      </template>
      <div class="current-area-info" v-if="isDistrictLevel">
        <button class="back-btn" @click="backToCenterMap">返回全国地图</button>
        <div class="area-info-content">
          当前区域: {{ currentAreaName }} ({{ getMapLevelName(mapLevel) }})
        </div>
      </div>
    </div>
    <div class="left-panel">
      <div class="left-content">
        <div class="left-element">
          <TitleBlock v-if="isAdmin" title="基础数据" link="D001729sja68j1rfuestgzsfuy55" />
          <div v-if="isAdmin" style="height: 11vh;">
            <OrgCount :areaCode="areaCode" :isAdmin="isAdmin" />
          </div>

          <TitleBlock v-if="isAdmin" title="监控点在线率" link="D001729DeviceChannel" />
          <div v-if="isAdmin" style="height: 15vh; margin-top: 10px;">
            <DeviceOnline :areaCode="areaCode" />
          </div>

          <TitleBlock v-if="!isAdmin" title="运营数据" link="D288422RunDataRecords" />
          <div v-if="!isAdmin" style="height: 48vh;">
            <RunDataCount :areaCode="areaCode" />
          </div>
          <TitleBlock v-if="isAdmin" title="医院各地区分布统计TOP5" link="D001729sja68j1rfuestgzsfuy55" style="margin-top: 0px;" />
          <div v-if="isAdmin" style="height: 21vh; padding-left: 15px;">
            <OrgCityRateBar :areaCode="areaCode" />
          </div>

          <TitleBlock title="月度污水处理数据统计" link="D288422RunDataRecords" style="margin-top: 20px;" />
          <div style="height: 17vh; padding-left: 15px;">
            <TrendBox :areaCode="areaCode "/>
          </div>

        </div>
      </div>
    </div>
    <div class="right-panel">
      <div class="right-content">
        <div class="right-element">
          <TitleBlock title="感知数据" link="D001729AlarmEvent" style="margin-top: -30px;" />
          <div style="height: 20vh;">
            <AlarmCount :areaCode="areaCode" :lastAlarmData="lastAlarmData" />
          </div>

          <TitleBlock title="近8h数据上报趋势" link="D288422SensorEventData" />
          <div style="height: 15vh;">
            <LineToday :areaCode="areaCode" />
          </div>

          <TitleBlock v-model:modelValue="isShowEventList" :showExpandBtn="true" title="实时预警" style="margin-top: 30px;" link="D001729AlarmEvent" />
          <div v-if="isShowEventList" style="height: 22vh;">
            <EventList :areaCode="areaCode" :lastAlarmData="lastAlarmData" />
          </div>
          <div v-else style="height: 22vh;">
          </div>

          <!-- <TitleBlock title="近7天预警处置趋势" style="margin-top: 15px;" />
          <div style="height: 15vh;">
            <LineWeek :areaCode="areaCode" />
          </div> -->

          <TitleBlock title="最新工单" link="D288422WorkLog" style="margin-top: 15px;" />
          <div style="height: 15vh; padding-left: 15px;">
            <WorkOrderList :areaCode="areaCode" />
          </div>

        </div>
      </div>
    </div>
    <Footer />
    
    <!-- 对话框组件 -->
    <VideoManageDialog v-model="showVideoManageDialog" @refresh="handleVideoManageRefresh" />
    <ReportDialog :unitId="areaCode" v-model="showReportDialogVisible" />
  </div>
</template>

<style scoped lang="scss">
.screen-container {
  position: relative;
  width: 100%;
  height: 100vh;
  padding: 0;
  box-sizing: border-box;
  background: linear-gradient(to top, rgb(12, 45, 95), rgba(24, 70, 141, 1));
  overflow: hidden;
}

.map-wrapper {
  position: absolute;
  top: 80px;
  bottom: 45px;
  left: 480px;
  right: 480px;
  margin: auto;
  overflow: hidden;
  flex: 1;
  z-index: 10;
  border-radius: 8px;
}

.single-station-wrap {
  position: absolute;
  top: 5px;
  bottom: 25px;
  left: 5px;
  right: 5px;
  margin: auto;
  overflow: hidden;
  color: #fff;
  background: linear-gradient(to top, rgba(8, 23, 46, 0.3), rgba(8, 23, 46, 0.2));
  padding: 0;
  box-sizing: border-box;
  border-radius: 8px;
  z-index: 1000 !important;
}

.current-area-info {
  position: fixed;
  top: 90px;
  left: 520px;
  z-index: 10 !important;
  background-color: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.area-info-content {
  margin-right: 10px;
}

.back-btn {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  margin-right: 10px;
}

.back-btn:hover {
  background-color: #40a9ff;
}

.left-panel,
.right-panel {
  position: absolute;
  top: 0;
  bottom: 0;
  margin: auto;
  width: 460px;
  z-index: 10;
  background-size: 100% 100%;
  overflow: hidden;

  .left-content,
  .right-content {
    margin: 50px 0 15px 15px;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    display: flex;
    overflow: hidden;
  }
}

.left-panel {
  left: 0;
  background-size: 100% 100%;

  .left-content {
    background: url("@/assets/images/screen/left-panel-bg.png") no-repeat;
    background-size: 220px 100%;

    .left-element {
      margin: 30px 0 30px 50px;
      display: flex;
      flex-direction: column;
      flex: 1;
      padding: 25px 15px;
    }
  }
}

.right-panel {
  right: 0;
  background-size: 100% 100%;

  .right-content {
    width: 445px;
    margin: 50px 10px 15px 0;
    background: url("@/assets/images/screen/right-panel-bg.png") no-repeat right;
    background-size: 220px 100%;

    .right-element {
      margin: 30px 50px 30px 0;
      display: flex;
      flex-direction: column;
      flex: 1;
      padding: 25px 0;
    }
  }
}

.card-item {
  width: 100%;
}

/* 对话框组件样式 */
:deep(.el-dialog) {
  z-index: 9999 !important;
}

:deep(.el-dialog__wrapper) {
  z-index: 9998 !important;
}

:deep(.el-overlay) {
  z-index: 9997 !important;
}
</style>
